package com.qst.survey.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qst.survey.entity.Question;
import com.qst.survey.entity.QuestionAnswer;
import com.qst.survey.entity.QuestionTopic;
import com.qst.survey.entity.Type;
import com.qst.survey.mapper.QuestionAnswerMapper;
import com.qst.survey.mapper.QuestionMapper;
import com.qst.survey.mapper.QuestionTopicMapper;
import com.qst.survey.mapper.TypeMapper;
import com.qst.survey.pojo.Result;
import com.qst.survey.pojo.StatusCode;
import com.qst.survey.pojo.TopicData;
import com.qst.survey.service.AnswerService;
import com.qst.survey.service.QuestionService;
import com.qst.survey.service.QuestionTopicService;
import com.qst.survey.service.UserReplyService;
import com.qst.survey.util.ColorUtil;
import com.qst.survey.util.FastDFSUtil;
import com.qst.survey.vo.BarVO;
import com.qst.survey.vo.DataVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.multipart.MultipartFile;

import java.sql.ResultSet;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @Description: QuestionTopic的ServiceImpl层方法
 */
@Service
public class QuestionServiceImpl implements QuestionService {

    @Autowired
    QuestionMapper questionMapper;

    @Autowired
    QuestionTopicService questionTopicService;
    @Autowired
    QuestionAnswerMapper questionAnswerMapper;
    @Autowired
    QuestionTopicMapper questionTopicMapper;
    @Autowired
    FastDFSUtil fastDFSUtil;
    @Autowired
    TypeMapper typeMapper;


    /**
     * @param question:
     * @return void
     * @description: TODO 添加投票
     */
    @Transactional
    @Override
    public Integer addQuestion(Question question, MultipartFile file) {
        String fileSrc = null;
        if (file != null) {
            fileSrc = fastDFSUtil.uploadFile(file);
        }
        System.out.println(fileSrc);
        question.setFileSrc(fileSrc);

        //存入问题
        int insert = questionMapper.insert(question);
        Integer id = 0;
        if (insert != 0) {
            id = question.getId();
        }
        return id;
    }

    /**
     * @param page:
     * @param type:
     * @return java.util.List<com.qst.survey.entity.Question>
     * @description: TODO 根据用户查找的类型 Type 查找投票
     */
    @Override
    @Transactional
    public Page<Question> queryByType(Page page, int type) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("type", type);
        queryWrapper.eq("is_over", 0);
        queryWrapper.orderByDesc("heat_degree");
        Page<Question> page2 = questionMapper.selectPage(page, queryWrapper);
        for (Question record : page2.getRecords()) {
            Type type1 = typeMapper.selectById(record.getType());
            record.setMsg(type1.getMsg());
        }
        return page2;
    }

    /**
     * @param page:
     * @param userId:
     * @return java.util.List<com.qst.survey.entity.Question>
     * @description: TODO 根据用户id查询投票
     */
    @Override
    @Transactional
    public Page<Question> queryByUserId(Page page, int userId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userId);
        queryWrapper.orderByDesc("id");
        Page<Question> page2 = questionMapper.selectPage(page, queryWrapper);
        return page2;
    }

    /**
     * @param id 投票id
     * @return java.util.List<com.qst.survey.entity.Question>
     * @description TODO  用户id查询所有投票
     */
    @Override
    @Transactional
    public List<Question> queryListById(Integer id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", id);
        queryWrapper.orderByDesc("id");
        List<Question> questions = questionMapper.selectList(queryWrapper);
        return questions;
    }


    /**
     * @param page:
     * @return com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.qst.survey.entity.Question>
     * @description: TODO 查询所有的页面
     */
    @Override
    @Transactional
    public Page<Question> queryAll(Page page) {
        Date date=new Date();
        //使用结束时间来判断,检查那些没有结束的投票,是否该结束
        QueryWrapper queryWrapper1=new QueryWrapper();
        queryWrapper1.eq("is_over",0);
        List<Question> questions = questionMapper.selectList(queryWrapper1);
        Iterator iterator=questions.iterator();
        while(iterator.hasNext()){
            Question question = (Question) iterator.next();
            if(question.getOverTime().before(date)){
                question.setIsOver(1);
                question.setOverTime(null);
                questionMapper.updateById(question);
            }
        }
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("heat_degree");
        queryWrapper.eq("is_over",0);
        Page<Question> page1 = questionMapper.selectPage(page, queryWrapper);
        //设置类型信息
        for (Question record : page1.getRecords()) {
            Type type1 = typeMapper.selectById(record.getType());
            record.setMsg(type1.getMsg());
        }
        return page1;
    }

    /**
     * @param questionId:
     * @return java.util.ArrayList<com.qst.survey.entity.QuestionTopic>
     * @description: TODO 通过一张卷子的id查询出所有的题目
     */
    @Override
    public Question findAllTopics(Integer questionId) {
        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("id", questionId);
        Question question = questionMapper.selectOne(queryWrapper1);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("question_id", questionId);
        List<QuestionTopic> questionTopics = questionTopicMapper.selectList(queryWrapper);
        for (int i = 0; i < questionTopics.size(); i++) {
            QuestionTopic topic = questionTopics.get(i);
            QuestionTopic topicAll = questionTopicService.findTopicAll(topic.getId());
            question.getTopics().add(topicAll);
        }
        return question;
    }

    /**
     * @param id 投票id
     * @return java.util.List<com.qst.survey.entity.Question>
     * @description TODO 查找被删除的投票
     */
    @Override
    public List<Question> queryDeleteListById(Integer id) {

        List<Question> allDelete = questionMapper.findAllDelete(id);
        return allDelete;
    }

    /**
     * @param questionId 投票id
     * @return java.lang.Integer
     * @description TODO   删除一张投票
     */
    @Override
    public Integer deleteOneQuestion(Integer questionId) {
        int i = questionMapper.deleteById(questionId);
        return i;
    }

    /**
     * @param questionId ：投票id
     * @return java.lang.Integer
     * @description TODO   恢复一张投票
     * @date 2021/4/2
     */
    @Override
    public Integer restoreOneQuestion(Integer questionId) {
        Integer integer = questionMapper.restoreQuestion(questionId);
        return integer;
    }

    /**
     * @param id 投票id
     * @return com.qst.survey.entity.Question
     * @description TODO   通过投票id来查出投票
     * @date 2021/4/2
     */
    @Override
    public Question findQuestionById(int id) {
        Question question = questionMapper.selectById(id);
        //封装类型的字符串到对象中
        Type type = typeMapper.selectById(question.getType());
        question.setMsg(type.getMsg());
        return question;
    }

    /**
     * @param question ：投票对象
     * @return boolean
     * @description TODO 修改一个问题对象
     */
    @Override
    public boolean editQuestion(Question question) {
        Date date = new Date();
        if(question.getOverTime().after(date)){
            question.setIsOver(0);
        }
        System.out.println("***************************");
        System.out.println(question.getOverTime());
        int edit = questionMapper.updateById(question);
        System.out.println(question.getOverTime());
        return edit > 0;
    }

    /**
     * @param id 投票id
     * @return boolean
     * @description TODO 通过一个id来删除一个问题对象
     */
    @Override
    public boolean removeQuestion(int id) {
        int remove = questionMapper.deleteById(id);
        return remove > 0;
    }

    /**
     * @param paperId ：投票id
     * @return java.util.List
     * @description TODO 查出所有投票题目
     */
    @Override
    public List findAllData(Integer paperId) {
        ArrayList<TopicData> dataArrayList = new ArrayList<>();
        List<QuestionTopic> allData = questionTopicService.findAllData(paperId);
        for (QuestionTopic topic : allData
        ) {
            TopicData topicData = questionTopicService.findTopicData(topic.getId());
            dataArrayList.add(topicData);
        }
        return dataArrayList;
    }

    /**
     * @param Theme ：投票名称
     * @return java.util.List<com.qst.survey.entity.Question>
     * @description TODO   通过投票名称来查出投票来
     */
    @Override
    public List<Question> findQuestionByTheme(String Theme) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.like("Theme", Theme);
        queryWrapper.orderByDesc("heat_degree");
        List<Question> list = questionMapper.selectList(queryWrapper);
        for (Question question : list) {
            //封装类型的字符串到对象中
            Type type = typeMapper.selectById(question.getType());
            question.setMsg(type.getMsg());
        }
        return list;
    }

    /**
     * @param page ：分页对象
     * @return com.baomidou.mybatisplus.extension.plugins.pagination.Page
     * @description TODO   查出分页的模板投票
     */
    @Override
    public Page findAllTemplate(Page page) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("is_demo", 1);
        return questionMapper.selectPage(page, queryWrapper);
    }

    /**
     * @param page 分页类
     * @param type 类型
     * @return com.baomidou.mybatisplus.extension.plugins.pagination.Page
     * @description TODO   通过类型来查出投票
     */
    @Override
    public Page findTypeTemplate(Page page, int type) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("type", type);
        queryWrapper.eq("is_demo", 1);
        Page<Question> page2 = questionMapper.selectPage(page, queryWrapper);
        return page2;
    }

    /**
     * @param id     模板投票id
     * @param userId 用户id
     * @return int
     * @description TODO  复制一个模板投票
     */
    @Override
    public int createTemplate(Integer id, Integer userId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id", id);
        Question question = questionMapper.selectOne(queryWrapper);
        question.setId(null);
        question.setIsDemo(0);
        question.setUserId(userId);
        question.setCount(0);
        question.setHeatDegree(0);
        question.setCreateTime(null);
        question.setUpdateTime(null);
        questionMapper.insert(question);
        //通过以前的投票id来查找出所有的以前投票的问题
        List<QuestionTopic> topics = questionTopicService.findById(id);
        for (QuestionTopic topic : topics) {
            //记录以前问题的id
            int oldTopicId = topic.getId();
            //复制新的题目
            topic.setId(null);
            topic.setQuestionId(question.getId());
            questionTopicMapper.insert(topic);
            //判断是否是单选或者多选题
            if (topic.getAnswerType() != 0) {
                //找出单选多选的回答选项
                QueryWrapper queryWrapper1 = new QueryWrapper();
                queryWrapper1.eq("topic_id", oldTopicId);
                //通过以前的问题id来找出所有的以前的问题选项
                List<QuestionAnswer> answers = questionAnswerMapper.selectList(queryWrapper1);
                //插入一个新的问题
                for (QuestionAnswer answer : answers) {
                    //复制这些选项
                    answer.setId(null);
                    answer.setSelected(0);
                    answer.setTopicId(topic.getId());
                    questionAnswerMapper.insert(answer);
                }
            }
        }
        return question.getId();
    }

    /**
     * @param id 投票id
     * @description TODO  增加投票答复数
     */
    @Override
    public void addCount(int id) {
        Question question = questionMapper.selectById(id);
        question.setCount(question.getCount() + 1);
        int i = questionMapper.updateById(question);
        System.out.println(i);
    }

    /**
     * @return com.qst.survey.vo.BarVO
     * @description TODO 获得投票回答人数的折线图数据
     */
    @Override
    public BarVO getQueCountLine() {
        List<Question> questionList = questionMapper.selectList(null);
        ArrayList<String> xData = new ArrayList<>();
        ArrayList<DataVO> yData = new ArrayList<>();
        for (Question question : questionList) {
            xData.add(question.getId() + "");
            DataVO dataVO = new DataVO();
            dataVO.setValue(question.getCount());
            dataVO.setItemStyle(ColorUtil.createItemStyle(question.getCount()));
            yData.add(dataVO);
        }
        BarVO barVO = new BarVO();
        barVO.setXData(xData);
        barVO.setYData(yData);
        return barVO;
    }
    /**
     * @description  TODO 投票热度加1
     * @return boolean
     * @date 2021/4/4
     */
    @Override
    public boolean addHeatDegree(Integer id) {
        //取出来要热度加1的投票
        Question question = questionMapper.selectById(id);
        //question 热度键加1
        question.setHeatDegree(question.getHeatDegree()+1);
        int update=questionMapper.updateById(question);
        return update>0;
    }
    /**
     * @description  TODO 创建一个模板投票
     * @return boolean
     * @date 2021/4/4
     */
    @Override
    public boolean setTemplate(Question question) {
        question.setUserId(0);
        question.setHeatDegree(0);
        question.setCount(0);
        int res=questionMapper.updateById(question);
        return res>0;
    }
    /**
     * @param page ：分页类
     * @description  TODO  分页查出所有的投票(已经结束,和没有结束)
     * @return com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.qst.survey.entity.Question>
     * @date 2021/4/2
     */
    @Override
    public Page findAllQu(Page page) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        //根据结束结束排序
        queryWrapper.orderByAsc("over_time");
        Page<Question> page1 = questionMapper.selectPage(page, queryWrapper);
        //设置类型信息
        for (Question record : page1.getRecords()) {
            Type type1 = typeMapper.selectById(record.getType());
            record.setMsg(type1.getMsg());
        }
        return page1;
    }

    @Override
    public Page findByTypeALL(Page page, int type) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("type", type);
        //根据结束结束排序
        queryWrapper.orderByAsc("over_time");
        Page<Question> page2 = questionMapper.selectPage(page, queryWrapper);
        for (Question record : page2.getRecords()) {
            Type type1 = typeMapper.selectById(record.getType());
            record.setMsg(type1.getMsg());
        }
        return page2;
    }

}
